import { useEffect, useState } from "react";
import {
  Card,
  List,
  Typography,
  Pagination,
  Descriptions,
  Avatar,
  Tag,
  Spin,
  message,
  Empty,
  Row,
  Col,
  Statistic,
  Tabs,
  Button,
  Form,
  Input,
  InputNumber,
  Space,
  Modal,
  Popconfirm,
  Drawer,
  Select,
  Cascader,
} from "antd";
import MDEditor from "@uiw/react-md-editor";
import { useTheme } from "../contexts/ThemeContext";
import {
  UserOutlined,
  BookOutlined,
  EyeOutlined,
  CalendarOutlined,
  EditOutlined,
  TagOutlined,
  SaveOutlined,
  PlusOutlined,
  DeleteOutlined,
  BulbOutlined,
  MessageOutlined,
  StarOutlined,
} from "@ant-design/icons";
import { Link } from "react-router-dom";
import "antd/dist/reset.css";
import { getUserProfile, updateUser, forceLogout } from "../api/users";
import { uploadImage } from "../api/upload";
import {
  getUserArticles,
  createArticle,
  updateArticle,
  deleteArticle,
  generateTags,
  publishArticle,
} from "../api/articles";
import {
  getCommentsByUserId,
  updateComment,
  deleteComment,
} from "../api/comments";
import { getAllCategories } from "../api/category";

const { Title, Text } = Typography;
const { TextArea } = Input;

export default function Profile() {
  const { isDarkMode } = useTheme();
  const [userInfo, setUserInfo] = useState(null);
  const [articles, setArticles] = useState([]);
  const [total, setTotal] = useState(0);
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(5);
  const [loading, setLoading] = useState(false);
  const [userLoading, setUserLoading] = useState(false);
  const [avatarUploading, setAvatarUploading] = useState(false);
  // 头像上传处理
  const handleAvatarChange = async (e) => {
    const file = e.target.files[0];
    if (!file) return;
    setAvatarUploading(true);
    try {
      const res = await uploadImage(file);
      if (
        (res.code === 1 || res.code === 200) &&
        res.data &&
        res.data.oss_url
      ) {
        // 更新用户头像img字段
        const updateRes = await updateUser({
          ...userInfo,
          img: res.data.oss_url,
        });
        if (updateRes.code === 1) {
          message.success("头像上传成功");
          fetchUserInfo();
        } else {
          message.error(updateRes.msg || "头像更新失败");
        }
      } else {
        message.error(res.msg || "图片上传失败");
      }
    } catch (err) {
      message.error(err.message || "上传失败");
    } finally {
      setAvatarUploading(false);
    }
  };
  const [editMode, setEditMode] = useState(false);
  const [updateLoading, setUpdateLoading] = useState(false);
  const [form] = Form.useForm();
  const [allArticlesStats, setAllArticlesStats] = useState({
    totalViews: 0,
    publishedCount: 0,
  });

  // 文章管理相关状态
  const [articleDrawerVisible, setArticleDrawerVisible] = useState(false);
  const [editingArticle, setEditingArticle] = useState(null);
  const [articleForm] = Form.useForm();
  const [articleSubmitting, setArticleSubmitting] = useState(false);
  const [tagsGenerating, setTagsGenerating] = useState(false);

  // 分类相关状态
  const [categories, setCategories] = useState([]); // 级联选择器用的数据
  const [originalCategories, setOriginalCategories] = useState([]); // 原始分类数据
  const [categoryLoading, setCategoryLoading] = useState(false);

  // 评论相关状态
  const [userComments, setUserComments] = useState([]);
  const [commentsTotal, setCommentsTotal] = useState(0);
  const [commentsLoading, setCommentsLoading] = useState(false);
  const [commentPage, setCommentPage] = useState(1);
  const [commentPageSize, setCommentPageSize] = useState(5);
  const [editingComment, setEditingComment] = useState(null);
  const [commentModalVisible, setCommentModalVisible] = useState(false);
  const [commentForm] = Form.useForm();

  // 获取用户评论
  const fetchUserComments = async () => {
    const userId = getCurrentUserId();
    if (!userId) {
      message.error("未找到用户信息");
      return;
    }

    setCommentsLoading(true);
    try {
      const res = await getCommentsByUserId(userId, {
        page: commentPage,
        size: commentPageSize,
      });
      setUserComments(res.data.list || []);
      setCommentsTotal(res.data.total || 0);
    } catch (error) {
      console.error("获取用户评论失败:", error);
      message.error(error.message || "获取用户评论失败");
      setUserComments([]);
      setCommentsTotal(0);
    } finally {
      setCommentsLoading(false);
    }
  };

  // 处理编辑评论
  const handleEditComment = (comment) => {
    setEditingComment(comment);
    commentForm.setFieldsValue({
      content: comment.content,
      star: comment.star,
    });
    setCommentModalVisible(true);
  };

  // 处理删除评论
  const handleDeleteComment = async (commentId) => {
    try {
      await deleteComment(commentId);
      message.success("删除评论成功");
      fetchUserComments();
    } catch (error) {
      console.error("删除评论失败:", error);
      message.error(error.message || "删除评论失败");
    }
  };

  // 提交评论修改
  const handleSubmitComment = async (values) => {
    if (!editingComment) return;

    try {
      await updateComment({
        id: editingComment.id,
        content: values.content,
        star: values.star,
        articleTitle: editingComment.articleTitle,
        username: editingComment.username,
      });

      message.success("评论修改成功");
      setCommentModalVisible(false);
      commentForm.resetFields();
      setEditingComment(null);
      fetchUserComments();
    } catch (error) {
      console.error("修改评论失败:", error);
      message.error(error.message || "修改评论失败");
    }
  };

  // 获取当前用户ID
  const getCurrentUserId = () => {
    return localStorage.getItem("userId");
  };

  // 获取用户个人信息
  const fetchUserInfo = async () => {
    const userId = getCurrentUserId();
    if (!userId) {
      message.error("未找到用户信息");
      return;
    }

    setUserLoading(true);
    try {
      const res = await getUserProfile(userId);
      if (res.code === 1 && res.data) {
        // 用户信息已包含登录状态，直接使用
        setUserInfo(res.data);

        // 同时初始化表单数据
        form.setFieldsValue({
          name: res.data.name,
          email: res.data.email,
          age: res.data.age,
          password: res.data.password || "",
        });
      } else {
        message.error("获取用户信息失败");
      }
    } catch (error) {
      console.error("获取用户信息失败:", error);
      message.error(error.message || "获取用户信息失败");
    } finally {
      setUserLoading(false);
    }
  };

  // 保存用户信息
  const handleSaveUserInfo = async () => {
    try {
      const values = await form.validateFields();
      setUpdateLoading(true);

      const updateData = {
        id: userInfo.id,
        name: values.name,
        email: values.email,
        age: values.age,
        role: userInfo.role, // 保持原有角色
      };

      // 只有当密码存在且不为空时才包含密码字段
      if (values.password && values.password.trim()) {
        updateData.password = values.password.trim();
      }

      const res = await updateUser(updateData);
      if (res.code === 1) {
        message.success("个人信息更新成功");
        setEditMode(false);
        // 重新获取用户信息
        fetchUserInfo();
      } else {
        message.error(res.msg || "更新失败");
      }
    } catch (error) {
      console.error("更新用户信息失败:", error);
      message.error(error.message || "更新用户信息失败");
    } finally {
      setUpdateLoading(false);
    }
  };

  // 取消编辑
  const handleCancelEdit = () => {
    setEditMode(false);
    // 重置表单数据
    form.setFieldsValue({
      name: userInfo.name,
      email: userInfo.email,
      age: userInfo.age,
      password: userInfo.password || "", // 恢复真实的密码
    });
  };

  // 获取用户统计数据（所有文章）
  const fetchUserStats = async () => {
    const userId = getCurrentUserId();
    if (!userId) return;

    try {
      // 获取所有文章来计算统计数据
      const res = await getUserArticles(userId, { page: 1, size: 9999 });
      const allArticles = res.list || [];

      const totalViews = allArticles.reduce(
        (sum, article) => sum + (article.views || 0),
        0
      );
      const publishedCount = allArticles.filter(
        (article) => article.status === 1
      ).length;

      setAllArticlesStats({ totalViews, publishedCount });
    } catch (error) {
      console.error("获取用户统计数据失败:", error);
    }
  };

  // 加载分类数据
  const loadCategories = async () => {
    try {
      setCategoryLoading(true);
      const response = await getAllCategories();
      if (response.code === 1 && response.data) {
        const originalData = response.data.list || [];
        console.log("Profile加载的分类数据:", originalData);

        // 保存原始数据
        setOriginalCategories(originalData);

        // 转换为级联选择器需要的数据格式
        const cascaderData = originalData.map((category) => ({
          value: category.id,
          label: category.name,
          children:
            category.subCategories?.map((subCategory) => ({
              value: subCategory.id,
              label: subCategory.name,
            })) || [],
        }));
        console.log("Profile级联选择器数据:", cascaderData);
        setCategories(cascaderData);
      }
    } catch (error) {
      console.error("加载分类失败:", error);
      message.error("加载分类失败");
    } finally {
      setCategoryLoading(false);
    }
  };

  const fetchUserArticles = async () => {
    const userId = getCurrentUserId();
    if (!userId) {
      message.error("未找到用户信息");
      return;
    }

    setLoading(true);
    try {
      const res = await getUserArticles(userId, { page, size: pageSize });
      console.log("用户文章API响应:", res);
      setArticles(res.list || []);
      setTotal(res.total || 0);
    } catch (error) {
      console.error("获取用户文章失败:", error);
      message.error(error.message || "获取用户文章失败");
      setArticles([]);
      setTotal(0);
    } finally {
      setLoading(false);
    }
  };

  // 处理新建文章
  const handleCreateArticle = () => {
    setEditingArticle(null);
    articleForm.resetFields();
    setArticleDrawerVisible(true);
  };

  // 处理编辑文章
  const handleEditArticle = (article) => {
    setEditingArticle(article);

    console.log("编辑文章:", article);
    console.log("原始分类数据:", originalCategories);
    console.log("级联选择器数据:", categories);
    console.log("文章的子分类ID:", article.subCategoryId);

    // 设置基本字段
    articleForm.setFieldsValue({
      title: article.title,
      content: article.content,
      tags: article.tags || [], // 直接使用数组格式
      status: article.status,
    });

    // 如果分类数据已经加载完成，立即设置分类路径
    if (originalCategories.length > 0 && article.subCategoryId) {
      const categoryPath = findCategoryPath(article.subCategoryId);
      console.log("找到的分类路径:", categoryPath);
      articleForm.setFieldsValue({ categoryPath });
    }

    setArticleDrawerVisible(true);
  };

  // 查找分类路径的辅助函数
  const findCategoryPath = (subCategoryId) => {
    if (!subCategoryId || !originalCategories.length) return [];

    for (const category of originalCategories) {
      const subCategory = category.subCategories?.find(
        (sub) => sub.id === subCategoryId
      );
      if (subCategory) {
        return [category.id, subCategory.id];
      }
    }
    return [];
  };

  // 处理删除文章
  const handleDeleteArticle = async (articleId) => {
    try {
      await deleteArticle(articleId);
      message.success("删除文章成功");
      // 刷新文章列表
      fetchUserArticles();
      fetchUserStats();
    } catch (error) {
      console.error("删除文章失败:", error);
      message.error(error.message || "删除文章失败");
    }
  };

  // 处理发布文章
  const handlePublishArticle = async (articleId) => {
    try {
      await publishArticle(articleId);
      message.success("文章发布成功");
      // 刷新文章列表
      fetchUserArticles();
      fetchUserStats();
    } catch (error) {
      console.error("发布文章失败:", error);
      message.error(error.message || "发布文章失败");
    }
  };

  // 生成标签
  const handleGenerateTags = async () => {
    const content = articleForm.getFieldValue("content");
    if (!content || !content.trim()) {
      message.warning("请先输入文章内容");
      return;
    }

    setTagsGenerating(true);
    try {
      const response = await generateTags(content);
      if (response.code === 1 && response.data) {
        // 将返回的标签字符串转换为数组
        const generatedTags = response.data.split(",").map((tag) => tag.trim());
        // 获取当前已有的标签
        const currentTags = articleForm.getFieldValue("tags") || [];
        // 合并标签并去重
        const allTags = [...new Set([...currentTags, ...generatedTags])];

        articleForm.setFieldsValue({
          tags: allTags,
        });
        message.success("标签生成成功");
      }
    } catch (error) {
      console.error("生成标签失败:", error);
      message.error("生成标签失败");
    } finally {
      setTagsGenerating(false);
    }
  };

  // 提交文章
  const handleSubmitArticle = async (values) => {
    const currentUsername = localStorage.getItem("username");
    if (!currentUsername) {
      message.error("未找到用户信息");
      return;
    }

    setArticleSubmitting(true);
    try {
      const articleData = {
        title: values.title,
        content: values.content,
        username: currentUsername, // 使用当前用户名
        tags: Array.isArray(values.tags)
          ? values.tags.join(",")
          : values.tags || "", // 将数组转换为逗号分隔的字符串
        status: values.status || 0,
      };

      // 如果选择了分类路径，使用新的子分类ID；否则保持原有的子分类ID
      if (values.categoryPath && values.categoryPath.length === 2) {
        articleData.subCategoryId = values.categoryPath[1];
      } else if (editingArticle && editingArticle.subCategoryId) {
        // 编辑模式下，如果没有选择新的分类，保持原有的子分类ID
        articleData.subCategoryId = editingArticle.subCategoryId;
      }

      if (editingArticle) {
        // 编辑文章
        articleData.id = editingArticle.id;
        await updateArticle(articleData);
        message.success("文章更新成功");
      } else {
        // 新建文章
        await createArticle(articleData);
        message.success("文章创建成功");
      }

      setArticleDrawerVisible(false);
      articleForm.resetFields();
      setEditingArticle(null);

      // 刷新文章列表和统计
      fetchUserArticles();
      fetchUserStats();
    } catch (error) {
      console.error("提交文章失败:", error);
      message.error(error.message || "提交文章失败");
    } finally {
      setArticleSubmitting(false);
    }
  };

  useEffect(() => {
    fetchUserInfo();
    fetchUserStats();
    loadCategories(); // 加载分类数据
    fetchUserComments(); // 加载用户评论
  }, []);

  useEffect(() => {
    fetchUserArticles();
  }, [page, pageSize]);

  useEffect(() => {
    fetchUserComments();
  }, [commentPage, commentPageSize]);

  // 当分类数据加载完成且正在编辑文章时，重新设置分类路径
  useEffect(() => {
    if (
      editingArticle &&
      originalCategories.length > 0 &&
      editingArticle.subCategoryId
    ) {
      const categoryPath = findCategoryPath(editingArticle.subCategoryId);
      if (categoryPath.length > 0) {
        console.log("Profile分类数据加载完成，重新设置分类路径:", categoryPath);
        articleForm.setFieldsValue({ categoryPath });
      }
    }
  }, [originalCategories, editingArticle]);

  return (
    <div style={{ maxWidth: 1200, margin: "20px auto", padding: "0 16px" }}>
      {/* 页面标题 */}
      <div style={{ textAlign: "center", marginBottom: 32 }}>
        <Title level={2} style={{ color: "#1890ff", marginBottom: 8 }}>
          <UserOutlined /> 个人中心
        </Title>
        <Text type="secondary" style={{ fontSize: 16 }}>
          基于Spring Boot的个人信息和发布文章界面
        </Text>
      </div>

      <Card
        style={{
          borderRadius: 12,
          boxShadow: isDarkMode
            ? "0 2px 12px rgba(0,0,0,0.3)"
            : "0 2px 12px #eee",
          backgroundColor: isDarkMode ? "#1f1f1f" : "#ffffff",
          borderColor: isDarkMode ? "#434343" : "#d9d9d9",
          transition: "all 0.3s ease",
        }}>
        <Tabs
          defaultActiveKey="1"
          size="large"
          items={[
            {
              key: "1",
              label: (
                <span>
                  <UserOutlined />
                  个人信息
                </span>
              ),
              children: (
                <div style={{ padding: "20px 0" }}>
                  <Spin spinning={userLoading}>
                    {userInfo ? (
                      <Row gutter={[32, 32]} align="middle">
                        {/* 左侧头像和基本信息 */}
                        <Col xs={24} md={8}>
                          <div style={{ textAlign: "center" }}>
                            <div
                              style={{
                                position: "relative",
                                display: "inline-block",
                              }}>
                              <Avatar
                                size={120}
                                src={userInfo.img}
                                icon={!userInfo.img && <UserOutlined />}
                                style={{
                                  backgroundColor: "#1890ff",
                                  marginBottom: 24,
                                  objectFit: "cover",
                                }}
                              />
                              <input
                                type="file"
                                accept="image/*"
                                style={{
                                  position: "absolute",
                                  left: 0,
                                  top: 0,
                                  width: "100%",
                                  height: "100%",
                                  opacity: 0,
                                  cursor: "pointer",
                                }}
                                title="点击更换头像"
                                onChange={handleAvatarChange}
                                disabled={avatarUploading}
                              />
                              {avatarUploading && (
                                <div
                                  style={{
                                    position: "absolute",
                                    left: 0,
                                    top: 0,
                                    width: "100%",
                                    height: "100%",
                                    background: "rgba(255,255,255,0.7)",
                                    display: "flex",
                                    alignItems: "center",
                                    justifyContent: "center",
                                    borderRadius: "50%",
                                  }}>
                                  <Spin />
                                </div>
                              )}
                            </div>
                            <div>
                              <Title level={3} style={{ marginBottom: 8 }}>
                                {userInfo.name}
                              </Title>
                              <Tag
                                color={
                                  userInfo.role === "admin" ? "red" : "blue"
                                }
                                style={{ fontSize: 14, padding: "4px 12px" }}>
                                {userInfo.role === "admin" ? "管理员" : "用户"}
                              </Tag>
                            </div>
                          </div>
                        </Col>

                        {/* 右侧详细信息 */}
                        <Col xs={24} md={16}>
                          <div
                            style={{
                              display: "flex",
                              justifyContent: "space-between",
                              alignItems: "center",
                              marginBottom: 16,
                            }}>
                            <Title level={4} style={{ marginBottom: 0 }}>
                              基本信息
                            </Title>
                            <Space>
                              {!editMode ? (
                                <Button
                                  type="primary"
                                  icon={<EditOutlined />}
                                  onClick={() => setEditMode(true)}>
                                  编辑资料
                                </Button>
                              ) : (
                                <>
                                  <Button
                                    type="primary"
                                    icon={<SaveOutlined />}
                                    loading={updateLoading}
                                    onClick={handleSaveUserInfo}>
                                    保存
                                  </Button>
                                  <Button onClick={handleCancelEdit}>
                                    取消
                                  </Button>
                                </>
                              )}
                            </Space>
                          </div>

                          {!editMode ? (
                            <Descriptions
                              bordered
                              column={{ xs: 1, sm: 2 }}
                              size="middle">
                              <Descriptions.Item label="用户名">
                                {userInfo.name}
                              </Descriptions.Item>
                              <Descriptions.Item label="邮箱">
                                {userInfo.email}
                              </Descriptions.Item>
                              <Descriptions.Item label="年龄">
                                {userInfo.age} 岁
                              </Descriptions.Item>
                              <Descriptions.Item label="用户ID">
                                {userInfo.id}
                              </Descriptions.Item>
                              <Descriptions.Item label="角色">
                                {userInfo.role === "admin"
                                  ? "管理员"
                                  : "普通用户"}
                              </Descriptions.Item>
                              <Descriptions.Item label="登录状态">
                                <div
                                  style={{
                                    display: "flex",
                                    alignItems: "center",
                                    gap: 8,
                                  }}>
                                  <Tag
                                    color={
                                      userInfo.loginStatus === 1
                                        ? "green"
                                        : "red"
                                    }>
                                    {userInfo.loginStatus === 1
                                      ? "已登录"
                                      : "未登录"}
                                  </Tag>
                                  {userInfo.loginStatus === 1 && (
                                    <Tag color="blue">
                                      🔌 {userInfo.onlineDeviceCount || 0}{" "}
                                      台设备
                                    </Tag>
                                  )}
                                </div>
                              </Descriptions.Item>
                            </Descriptions>
                          ) : (
                            <Form
                              form={form}
                              layout="vertical"
                              style={{
                                background: "#fafafa",
                                padding: "20px",
                                borderRadius: "8px",
                                border: "1px solid #d9d9d9",
                              }}>
                              <Row gutter={16}>
                                <Col xs={24} sm={12}>
                                  <Form.Item
                                    label="用户名"
                                    name="name"
                                    rules={[
                                      {
                                        required: true,
                                        message: "请输入用户名",
                                      },
                                      {
                                        min: 2,
                                        max: 20,
                                        message: "用户名长度为2-20个字符",
                                      },
                                    ]}>
                                    <Input placeholder="请输入用户名" />
                                  </Form.Item>
                                </Col>
                                <Col xs={24} sm={12}>
                                  <Form.Item
                                    label="邮箱"
                                    name="email"
                                    rules={[
                                      { required: true, message: "请输入邮箱" },
                                      {
                                        type: "email",
                                        message: "请输入有效的邮箱地址",
                                      },
                                    ]}>
                                    <Input placeholder="请输入邮箱" />
                                  </Form.Item>
                                </Col>
                                <Col xs={24} sm={12}>
                                  <Form.Item
                                    label="年龄"
                                    name="age"
                                    rules={[
                                      { required: true, message: "请输入年龄" },
                                      {
                                        type: "number",
                                        min: 1,
                                        max: 120,
                                        message: "请输入有效的年龄",
                                      },
                                    ]}>
                                    <InputNumber
                                      placeholder="请输入年龄"
                                      style={{ width: "100%" }}
                                      min={1}
                                      max={120}
                                    />
                                  </Form.Item>
                                </Col>
                                <Col xs={24} sm={12}>
                                  <Form.Item
                                    label="密码"
                                    name="password"
                                    rules={[
                                      {
                                        required: true,
                                        message: "请输入密码",
                                      },
                                      {
                                        min: 6,
                                        max: 20,
                                        message: "密码长度为6-20个字符",
                                      },
                                    ]}
                                    extra="可以查看和修改当前密码">
                                    <Input.Password placeholder="请输入密码" />
                                  </Form.Item>
                                </Col>
                                <Col xs={24} sm={12}>
                                  <Form.Item label="用户ID">
                                    <Input value={userInfo.id} disabled />
                                  </Form.Item>
                                </Col>
                                <Col xs={24} sm={12}>
                                  <Form.Item label="角色">
                                    <Input
                                      value={
                                        userInfo.role === "admin"
                                          ? "管理员"
                                          : "普通用户"
                                      }
                                      disabled
                                    />
                                  </Form.Item>
                                </Col>
                              </Row>
                            </Form>
                          )}

                          {/* 统计信息 */}
                          <div style={{ marginTop: 32 }}>
                            <Title level={4} style={{ marginBottom: 16 }}>
                              我的统计
                            </Title>
                            <Row gutter={16}>
                              <Col span={8}>
                                <Statistic
                                  title="发布文章"
                                  value={total}
                                  prefix={<BookOutlined />}
                                  valueStyle={{ color: "#1890ff" }}
                                />
                              </Col>
                              <Col span={8}>
                                <Statistic
                                  title="总阅读量"
                                  value={allArticlesStats.totalViews}
                                  prefix={<EyeOutlined />}
                                  valueStyle={{ color: "#52c41a" }}
                                />
                              </Col>
                              <Col span={8}>
                                <Statistic
                                  title="已发布"
                                  value={allArticlesStats.publishedCount}
                                  prefix={<EditOutlined />}
                                  valueStyle={{ color: "#722ed1" }}
                                />
                              </Col>
                            </Row>
                          </div>
                        </Col>
                      </Row>
                    ) : (
                      <Empty description="暂无用户信息" />
                    )}
                  </Spin>
                </div>
              ),
            },
            {
              key: "2",
              label: (
                <span>
                  <BookOutlined />
                  我的文章
                </span>
              ),
              children: (
                <div style={{ padding: "20px 0" }}>
                  {/* 文章标题和新建按钮 */}
                  <div
                    style={{
                      display: "flex",
                      justifyContent: "space-between",
                      alignItems: "center",
                      marginBottom: 24,
                    }}>
                    <Typography.Title level={4} style={{ margin: 0 }}>
                      文章列表
                    </Typography.Title>
                    <Button
                      type="primary"
                      icon={<PlusOutlined />}
                      onClick={handleCreateArticle}>
                      新建文章
                    </Button>
                  </div>

                  <Spin spinning={loading}>
                    {articles.length > 0 ? (
                      <>
                        <List
                          itemLayout="vertical"
                          size="large"
                          dataSource={articles}
                          renderItem={(article) => (
                            <List.Item
                              key={article.id}
                              actions={[
                                <span key="views">
                                  <EyeOutlined /> {article.views || 0}
                                </span>,
                                <span key="status">
                                  <Tag
                                    color={
                                      article.status === 1 ? "green" : "orange"
                                    }>
                                    {article.status === 1 ? "已发布" : "草稿"}
                                  </Tag>
                                </span>,
                                <span key="createAt">
                                  <CalendarOutlined />{" "}
                                  {article.createAt
                                    ? new Date(
                                        article.createAt
                                      ).toLocaleDateString()
                                    : "未知"}
                                </span>,
                                <Button
                                  key="edit"
                                  type="link"
                                  icon={<EditOutlined />}
                                  onClick={() => handleEditArticle(article)}>
                                  编辑
                                </Button>,
                                ...(article.status === 0
                                  ? [
                                      <Button
                                        key="publish"
                                        type="link"
                                        style={{ color: "#52c41a" }}
                                        onClick={() =>
                                          handlePublishArticle(article.id)
                                        }>
                                        发布
                                      </Button>,
                                    ]
                                  : []),
                                <Popconfirm
                                  key="delete"
                                  title="确定要删除这篇文章吗？"
                                  description="删除后无法恢复，请谨慎操作。"
                                  onConfirm={() =>
                                    handleDeleteArticle(article.id)
                                  }
                                  okText="确定"
                                  cancelText="取消">
                                  <Button
                                    type="link"
                                    danger
                                    icon={<DeleteOutlined />}>
                                    删除
                                  </Button>
                                </Popconfirm>,
                              ]}>
                              <List.Item.Meta
                                title={
                                  <Link
                                    to={`/article/${article.id}?from=profile`}
                                    style={{
                                      fontSize: 18,
                                      fontWeight: "bold",
                                      color: "#1890ff",
                                    }}>
                                    {article.title}
                                  </Link>
                                }
                                description={
                                  <>
                                    <div
                                      style={{
                                        display: "flex",
                                        alignItems: "center",
                                        flexWrap: "wrap",
                                      }}>
                                      <Text>作者：{article.username}</Text>
                                      <span style={{ marginLeft: 16 }}></span>
                                      {article.tags &&
                                        article.tags.map((tag, index) => (
                                          <Tag color="blue" key={tag + index}>
                                            {tag}
                                          </Tag>
                                        ))}
                                    </div>
                                    <div style={{ marginTop: 2 }}>
                                      <Text type="secondary">
                                        分类：{article.categoryName || "-"}
                                      </Text>
                                      <span style={{ margin: "0 8px" }}></span>
                                      <Text type="secondary">
                                        子分类：{article.subCategoryName || "-"}
                                      </Text>
                                    </div>
                                  </>
                                }
                              />
                              {/* 预览时隐藏markdown格式，仅显示纯文本摘要 */}
                              <Text
                                ellipsis={{ rows: 2, expandable: false }}
                                style={{
                                  color: "#666",
                                  fontSize: 14,
                                  lineHeight: 1.6,
                                }}>
                                {article.content &&
                                  article.content
                                    .replace(/[#*_`>\-\[\]!\(\)\n\r]/g, "")
                                    .slice(0, 100)}
                              </Text>
                            </List.Item>
                          )}
                        />
                        <div style={{ textAlign: "center", marginTop: 32 }}>
                          <Pagination
                            current={page}
                            pageSize={pageSize}
                            total={total}
                            showSizeChanger
                            pageSizeOptions={["3", "5", "10", "20"]}
                            onChange={(p, s) => {
                              setPage(p);
                              if (s !== pageSize) {
                                setPageSize(s);
                                setPage(1);
                              }
                            }}
                            showTotal={(t, range) =>
                              `第 ${range[0]}-${range[1]} 条，共 ${t} 篇文章`
                            }
                            showQuickJumper
                          />
                        </div>
                      </>
                    ) : (
                      <Empty
                        description="暂无发布的文章"
                        image={Empty.PRESENTED_IMAGE_SIMPLE}
                        style={{ padding: "60px 0" }}>
                        <Button
                          type="primary"
                          icon={<PlusOutlined />}
                          onClick={handleCreateArticle}>
                          创建第一篇文章
                        </Button>
                      </Empty>
                    )}
                  </Spin>
                </div>
              ),
            },
            {
              key: "3",
              label: (
                <span>
                  <MessageOutlined />
                  我的评论
                </span>
              ),
              children: (
                <div style={{ padding: "20px 0" }}>
                  {/* 评论标题 */}
                  <div
                    style={{
                      display: "flex",
                      justifyContent: "space-between",
                      alignItems: "center",
                      marginBottom: 24,
                    }}>
                    <Typography.Title level={4} style={{ margin: 0 }}>
                      我的评论列表
                    </Typography.Title>
                    <Typography.Text type="secondary">
                      共 {commentsTotal} 条评论
                    </Typography.Text>
                  </div>

                  <Spin spinning={commentsLoading}>
                    {userComments.length > 0 ? (
                      <>
                        <List
                          itemLayout="vertical"
                          size="large"
                          dataSource={userComments}
                          renderItem={(comment) => (
                            <List.Item
                              key={comment.id}
                              actions={[
                                <span key="star">
                                  <StarOutlined style={{ color: "#faad14" }} />{" "}
                                  {typeof comment.star === "number"
                                    ? comment.star.toFixed(1)
                                    : comment.star}
                                </span>,
                                <span key="time">
                                  <CalendarOutlined />{" "}
                                  {comment.createTime
                                    ? new Date(
                                        comment.createTime
                                      ).toLocaleDateString()
                                    : "未知"}
                                </span>,
                                <Button
                                  key="edit"
                                  type="link"
                                  icon={<EditOutlined />}
                                  onClick={() => handleEditComment(comment)}>
                                  编辑
                                </Button>,
                                <Popconfirm
                                  key="delete"
                                  title="确定要删除这条评论吗？"
                                  description="删除后无法恢复，请谨慎操作。"
                                  onConfirm={() =>
                                    handleDeleteComment(comment.id)
                                  }
                                  okText="确定"
                                  cancelText="取消">
                                  <Button
                                    type="link"
                                    danger
                                    icon={<DeleteOutlined />}>
                                    删除
                                  </Button>
                                </Popconfirm>,
                              ]}>
                              <List.Item.Meta
                                title={
                                  <div
                                    style={{
                                      display: "flex",
                                      alignItems: "center",
                                      gap: 12,
                                    }}>
                                    <Typography.Text
                                      strong
                                      style={{ fontSize: 16 }}>
                                      评论文章：{comment.articleTitle}
                                    </Typography.Text>
                                    <Tag color="blue">ID: {comment.id}</Tag>
                                  </div>
                                }
                                description={
                                  <div style={{ marginTop: 8 }}>
                                    <div
                                      style={{
                                        backgroundColor: isDarkMode
                                          ? "#262626"
                                          : "#f6f6f6",
                                        padding: "12px",
                                        borderRadius: "6px",
                                        lineHeight: 1.6,
                                        marginBottom: 8,
                                      }}>
                                      {comment.content}
                                    </div>
                                    <div
                                      style={{ fontSize: 12, color: "#999" }}>
                                      创建时间：
                                      {comment.createTime
                                        ? new Date(
                                            comment.createTime
                                          ).toLocaleString()
                                        : "未知"}
                                      {comment.updateTime &&
                                        comment.updateTime !==
                                          comment.createTime && (
                                          <>
                                            {" | "}
                                            更新时间：
                                            {new Date(
                                              comment.updateTime
                                            ).toLocaleString()}
                                          </>
                                        )}
                                    </div>
                                  </div>
                                }
                              />
                            </List.Item>
                          )}
                        />

                        {/* 评论分页 */}
                        <div style={{ textAlign: "center", marginTop: 32 }}>
                          <Pagination
                            current={commentPage}
                            pageSize={commentPageSize}
                            total={commentsTotal}
                            showSizeChanger
                            pageSizeOptions={["5", "10", "20"]}
                            onChange={(p, s) => {
                              setCommentPage(p);
                              if (s !== commentPageSize) {
                                setCommentPageSize(s);
                                setCommentPage(1);
                              }
                            }}
                            showTotal={(t, range) =>
                              `第 ${range[0]}-${range[1]} 条，共 ${t} 条评论`
                            }
                            showQuickJumper
                          />
                        </div>
                      </>
                    ) : (
                      <Empty
                        description="暂无评论"
                        image={Empty.PRESENTED_IMAGE_SIMPLE}
                        style={{ padding: "60px 0" }}>
                        <Typography.Text type="secondary">
                          您还没有发表过评论，快去文章页面发表您的第一条评论吧！
                        </Typography.Text>
                      </Empty>
                    )}
                  </Spin>
                </div>
              ),
            },
          ]}
        />
      </Card>

      {/* 评论编辑模态框 */}
      <Modal
        title="编辑评论"
        open={commentModalVisible}
        onCancel={() => {
          setCommentModalVisible(false);
          commentForm.resetFields();
          setEditingComment(null);
        }}
        footer={null}
        width={600}>
        <Form
          form={commentForm}
          layout="vertical"
          onFinish={handleSubmitComment}>
          {/* 显示文章标题（只读） */}
          <Form.Item label="评论文章">
            <Input
              value={editingComment?.articleTitle}
              disabled
              style={{ backgroundColor: isDarkMode ? "#262626" : "#f5f5f5" }}
            />
          </Form.Item>

          <Form.Item
            name="content"
            label="评论内容"
            rules={[
              { required: true, message: "请输入评论内容" },
              { max: 1000, message: "评论内容不能超过1000个字符" },
            ]}>
            <TextArea
              placeholder="请输入评论内容"
              rows={4}
              showCount
              maxLength={1000}
            />
          </Form.Item>

          <Form.Item
            name="star"
            label="评分"
            rules={[
              { required: true, message: "请输入评分" },
              {
                type: "number",
                min: 0,
                max: 10,
                message: "评分必须在0-10之间",
              },
            ]}>
            <InputNumber
              min={0}
              max={10}
              step={0.1}
              precision={1}
              placeholder="请输入评分(0-10)"
              style={{ width: "100%" }}
            />
          </Form.Item>

          <Form.Item style={{ marginBottom: 0, textAlign: "right" }}>
            <Space>
              <Button
                onClick={() => {
                  setCommentModalVisible(false);
                  commentForm.resetFields();
                  setEditingComment(null);
                }}>
                取消
              </Button>
              <Button type="primary" htmlType="submit">
                保存修改
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>

      {/* 文章编辑抽屉 */}
      <Drawer
        title={editingArticle ? "编辑文章" : "新建文章"}
        placement="right"
        onClose={() => {
          setArticleDrawerVisible(false);
          articleForm.resetFields();
          setEditingArticle(null);
        }}
        open={articleDrawerVisible}
        width={800}
        extra={
          <Space>
            <Button
              onClick={() => {
                setArticleDrawerVisible(false);
                articleForm.resetFields();
                setEditingArticle(null);
              }}>
              取消
            </Button>
            <Button
              type="primary"
              loading={articleSubmitting}
              onClick={() => articleForm.submit()}>
              {editingArticle ? "更新" : "发布"}
            </Button>
          </Space>
        }>
        <Form
          form={articleForm}
          layout="vertical"
          onFinish={handleSubmitArticle}>
          <Form.Item
            label="文章标题"
            name="title"
            rules={[
              { required: true, message: "请输入文章标题" },
              { min: 1, max: 100, message: "标题长度为1-100个字符" },
            ]}>
            <Input placeholder="请输入文章标题" />
          </Form.Item>

          <Form.Item
            label="文章内容 (支持Markdown)"
            name="content"
            rules={[
              { required: true, message: "请输入文章内容" },
              { min: 10, message: "内容至少10个字符" },
            ]}>
            <MDEditor
              height={300}
              placeholder="请输入文章内容，支持Markdown语法"
            />
          </Form.Item>

          <Form.Item
            label={
              <Space>
                <span>文章标签</span>
                <Button
                  type="link"
                  size="small"
                  icon={<BulbOutlined />}
                  loading={tagsGenerating}
                  onClick={handleGenerateTags}>
                  AI生成标签
                </Button>
              </Space>
            }
            name="tags">
            <Select
              mode="tags"
              placeholder="请输入标签并按回车添加，或点击右侧按钮智能生成"
              tokenSeparators={[","]}
              allowClear
              style={{ width: "100%" }}>
              {articles
                .flatMap((article) => article.tags)
                .filter((tag, index, arr) => arr.indexOf(tag) === index) // 去重
                .map((tag) => (
                  <Select.Option key={tag} value={tag}>
                    {tag}
                  </Select.Option>
                ))}
            </Select>
          </Form.Item>

          <Form.Item name="categoryPath" label="文章分类">
            <Cascader
              options={categories}
              placeholder="请选择文章分类（可选）"
              changeOnSelect
              loading={categoryLoading}
              showSearch={{
                filter: (inputValue, path) =>
                  path.some(
                    (option) =>
                      option.label
                        .toLowerCase()
                        .indexOf(inputValue.toLowerCase()) > -1
                  ),
              }}
              style={{ width: "100%" }}
            />
          </Form.Item>

          <Form.Item label="发布状态" name="status" initialValue={1}>
            <Select>
              <Select.Option value={0}>草稿</Select.Option>
              <Select.Option value={1}>发布</Select.Option>
            </Select>
          </Form.Item>
        </Form>
      </Drawer>
    </div>
  );
}
